<?php
// 路径分隔符辅助函数 - 跨平台兼容
if (!function_exists('join_path')) {
    function join_path(...$parts) {
        return implode(DIRECTORY_SEPARATOR, $parts);
    }
}
$project_root = realpath(dirname(__DIR__));
if ($project_root === false) {
    die('Failed to resolve project root directory');
}
// 启用错误报告（仅在开发环境中）
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


require_once join_path($project_root, 'vendor', 'autoload.php');


use Core\Container;
use Core\Router;
use Core\Request;
use Core\ExceptionHandler;

// 设置时区
date_default_timezone_set('Asia/Shanghai');

// 加载配置
$appConfig = require join_path($project_root, 'config', 'app.php');
$dbConfig = require join_path($project_root, 'config', 'database.php');

// 初始化容器
$container = new Container();

// 绑定配置
$container->singleton('config.app', function() use ($appConfig) {
    return $appConfig;
});

$container->singleton('config.database', function() use ($dbConfig) {
    return $dbConfig;
});

// 绑定核心组件
$container->singleton(Request::class, function() {
    return new Request();
});

$container->singleton(Router::class, function($container) {
    $router = new Router($container);
    
    // 加载路由定义
    require_once join_path(__DIR__, '..', 'routes', 'web.php');

    
    return $router;
});

$container->singleton(ExceptionHandler::class, function($container) {
    return new ExceptionHandler($container);
});

// 绑定中间件
$container->bind(\App\Middlewares\CorsMiddleware::class);
$container->bind(\App\Middlewares\AuthMiddleware::class);

// 处理请求
try {
    $request = $container->make(Request::class);
    $router = $container->make(Router::class);
    
    $response = $router->dispatch($request);
    $response->send();
} catch (Exception $e) {
    $handler = $container->make(ExceptionHandler::class);
    $response = $handler->handle($e);
    $response->send();
    
    // 在开发环境中显示详细错误信息
    if (getenv('APP_ENV') === 'development' || getenv('APP_DEBUG') === 'true') {
        echo "<h2>Error Details:</h2>";
        echo "<p><strong>Message:</strong> " . $e->getMessage() . "</p>";
        echo "<p><strong>File:</strong> " . $e->getFile() . ":" . $e->getLine() . "</p>";
        echo "<p><strong>Trace:</strong></p>";
        echo "<pre>" . $e->getTraceAsString() . "</pre>";
    }
}